/*
 *  Copyright 2020-2025 the original author or authors.
 *  You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import lombok.extern.slf4j.Slf4j;

/**
 * 脱敏数据通用算法
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id$$
 * @since 1.0
 */
@Slf4j
public class ConcealHelper {
    /*** 默认隐藏符号*/
    private static final String SYMBOL = "*";
    /*** 默认隐藏字符数量*/
    private static final int SIZE = 20;


    /**
     * 数据脱敏
     *
     * @param msg 原始消息
     * @return 脱敏消息
     */
    public static String toConceal(final String msg) {
        return toConceal(msg, SIZE, SYMBOL);
    }


    /**
     * 数据脱敏
     *
     * @param msg  原始消息
     * @param size 隐藏字符数量
     * @return 脱敏消息
     */
    public static String toConceal(final String msg, final int size) {
        return toConceal(msg, size, SYMBOL);
    }

    /**
     * 数据脱敏
     *
     * @param msg    原始消息
     * @param size   隐藏字符数量
     * @param symbol 符号
     * @return 脱敏消息
     */
    public static String toConceal(final String msg, final int size, final String symbol) {
        if (null == msg || "".equals(msg)) {
            return msg;
        }
        int len = msg.length();
        int pamaone = len / 2;
        int pamatwo = pamaone - 1;
        int pamathree = len % 2;
        StringBuilder sb = new StringBuilder();
        if (len <= 2) {
            if (pamathree == 1) {
                return symbol;
            }
            sb.append(symbol);
            sb.append(msg.charAt(len - 1));
        } else {
            if (pamatwo <= 0) {
                sb.append(msg.substring(0, 1));
                sb.append(symbol);
                sb.append(msg.substring(len - 1, len));

            } else if (pamatwo >= size / 2 && size + 1 != len) {
                int pamafive = (len - size) / 2;
                sb.append(msg.substring(0, pamafive));
                for (int i = 0; i < size; i++) {
                    sb.append(symbol);
                }
                if ((pamathree == 0 && size / 2 == 0) || (pamathree != 0 && size % 2 != 0)) {
                    sb.append(msg.substring(len - pamafive, len));
                } else {
                    sb.append(msg.substring(len - (pamafive + 1), len));
                }
            } else {
                int pamafour = len - 2;
                sb.append(msg.substring(0, 1));
                for (int i = 0; i < pamafour; i++) {
                    sb.append(symbol);
                }
                sb.append(msg.substring(len - 1, len));
            }
        }
        log.debug("\n原始数据：" + msg + "\n脱敏数据：" + sb.toString());
        return sb.toString();
    }
}
